package timer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import lottery.BetRecord;
import lottery.PayReward;
import lottery.RewardTime;

import org.hibernate.Session;

import code.lewdy.db.Database;
import code.lewdy.db.HibernateTemple;
import code.lewdy.db.JdbcTemple;
import code.lewdy.db.JdbcUtil;
import code.lewdy.lottery.LotteryHelper;
import code.lewdy.lottery.LotteryService;
import code.lewdy.lottery.OpenRewardNumber;
import code.lewdy.util.DataType;
import code.lewdy.web.response.ExtResponse;
import dao.HibernateSessionFactory;

public class TaskImpl implements Task
{
	
	LotteryService lotteryService = new LotteryService();
	JdbcUtil jdbc = new JdbcUtil(Database.TYPE_SQLSERVER);
	PayReward pay = new PayReward();
    LotteryHelper h = new LotteryHelper();
    

    Calendar c = Calendar.getInstance();

    int hour = c.get(Calendar.HOUR_OF_DAY);

    int minute = c.get(Calendar.MINUTE);

    int second = c.get(Calendar.SECOND);

    int secondCount = 0;

    int delayTime = 60; // 最多延时获取号码秒数

    public static void main(String[] args)
    {
        TaskImpl ti = new TaskImpl();
        ti.excute();
    }

    // 具体业务代码
    public void excute()
    {
        //System.out.println("Timer task excute()");
    	lotteryService.getOpenRewardsTask();
    }

    /**
     * 获取最新号码的任务
     * 
     * @author liuding,2012-4-23
     */
    public void getOpenRewardsTask()
    {
        ArrayList<RewardTime> rts = (ArrayList<RewardTime>) getCurrentRewardTimes();
        if (rts == null || rts.size() <= 0)
        {
            // System.out.println("该时间段没有时间调度任务");
            return;
        }
        for (RewardTime rt : rts)
        {
            int currentSp = rt.getOpenTimeSp() - (secondCount - rt.getBeginTime())
                    % rt.getOpenTimeSp();
            if (currentSp <= (rt.getBetEndTimeSp() + delayTime))
            { // 开奖时间过后延长/提前1分钟确认号码的获取
                // System.out.println("获取号码时段");
                // 截止投注时间
                Date betStopDate = new Date(new Date().getTime() - (rt.getEndTime() - currentSp));
                updateRewardNumber(rt.getLotteryId(), rt.getLotteryName(), betStopDate); // 更新号码到数据库
            }
            else
            {
                // System.out.println("非获取号码时段");
                return;
            }
        }
    }

    /**
     * 更新号码到数据库
     * 
     * @param lotteryId
     * @param lotteryName
     * @author liuding,2012-4-23
     */
    public void updateRewardNumber(int lotteryId, String lotteryName, Date betStopTime)
    {
        OpenRewardNumber num = null; // 最新号码
        num = h.getLatestRewardNumber(null, lotteryId, lotteryName);
        if (num == null)
        {
            // System.out.println("获取最新号码失败！");
            return;
        }
        num.setBetStopTime(betStopTime);
        @SuppressWarnings("unchecked")
		List<OpenRewardNumber> openNums = (List<OpenRewardNumber>) jdbc.list("code.lewdy.lottery.OpenRewardNumber", 
        		"where lotteryId=" + lotteryId + " and number='"
                    + num.getNumber() + "' ", 1, 1);
        int size = openNums.size();
        if (size > 0)
        {
            // System.out.println("已经更新为最新号码！");
        }
        else
        {
            // 更新最新号码到数据库
        	HibernateTemple.save(num);
        	//更新投注记录中的开奖号码
        	int updater = JdbcTemple.executeUpdate("update BetRecord set openRewardNumber='"+
        			num.getNumber()+"' where numberId='"+num.getPeriodNo()+"' and lotteryId="+
	        			num.getLotteryId());
        	payReward(num);
        	System.out.println(num.getLotteryName()+"OPEN NO UPDATING:BetRecord("+updater+")");
        }
    }
    
    /**按开奖号码自动派奖
     * @param num 开奖号码
     */
    @SuppressWarnings("unchecked")
	public void payReward(OpenRewardNumber num){
    	List<BetRecord> brs = (List<BetRecord>) jdbc.list("lottery.BetRecord", 
    			"where lotteryId="+num.getLotteryId()+" and numberId='"+num.getPeriodNo()+"'", 1, 10000);
    	for(BetRecord br : brs){
			if(br == null){
				return;
			}
			int results = pay.doPay(br);
		}
    }
    
    /**
     * 获取当前时间段内的时间管理
     * 
     * @return
     * @author liuding,2012-4-23
     */
    @SuppressWarnings("unchecked")
	public ArrayList<?> getCurrentRewardTimes()
    {
        Calendar c = Calendar.getInstance();
        hour = c.get(Calendar.HOUR_OF_DAY);
        minute = c.get(Calendar.MINUTE);
        second = c.get(Calendar.SECOND);
        secondCount = hour * 3600 + minute * 60 + second;
        
        String condition = "where beginTime < " + secondCount + " and endTime > "
        	+ secondCount;
        ArrayList<RewardTime> list = (ArrayList<RewardTime>) jdbc.list(RewardTime.class.getName(), condition, 1, 200);
        System.out.println("Timer check...size=>"+list.size());
        return list;
    }

}
